package com.fjec.market.rabbitmq.consumer;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fjec.common.protocol.FjecFruitsProto;
import com.fjec.market.entity.InfoBusiness;
import com.fjec.market.entity.InfoFarmer;
import com.fjec.market.entity.InfoPurchase;
import com.fjec.market.helper.MysqlShopNumHelper;
import com.fjec.market.service.IInfoBusinessService;
import com.fjec.market.service.IInfoFarmerService;
import com.fjec.market.service.IInfoPurchaseService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@Component
public class ShopNumConsumer {


    @Resource
    private IInfoPurchaseService purchaseService;

    @Resource
    private IInfoFarmerService farmerService;

    @Resource
    private IInfoBusinessService businessService;

    @Resource
    private MysqlShopNumHelper mysqlShopNumHelper;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "${fjec.market.shopnum.queue.name}",
                            durable = "${fjec.market.shopnum.queue.durable}"
                    ),
                    exchange = @Exchange(
                            value = "${fjec.market.shopnum.exchange.name}",
                            durable = "${fjec.market.shopnum.exchange.durable}",
                            type = "${fjec.market.shopnum.exchange.type}",
                            ignoreDeclarationExceptions = "${fjec.market.shopnum.exchange.ignoreDeclarationExceptions}"
                    ),
                    key = "${fjec.market.shopnum.router.key}"
            )
    )
    @RabbitHandler
    public void onShopNumGen(Message message, Channel channel, @Headers Map<String, Object> headers) throws Exception {
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        try {
            FjecFruitsProto.FjecFruitsMsg fjecFruitsMsg = FjecFruitsProto.FjecFruitsMsg.parseFrom(message.getBody());
            if (fjecFruitsMsg.hasShopNumGen()) {
                FjecFruitsProto.ShopNumGen shopNumGen = fjecFruitsMsg.getShopNumGen();
                switch (shopNumGen.getBusiType()) {
                    case 2:
                        this.handleFarmer(shopNumGen.getBusiId(), shopNumGen.getMarkCode());
                        break;
                    case 4:
                    case 3:
                    case 5:
                        this.handleBusiness(shopNumGen.getBusiId(), shopNumGen.getMarkCode());
                        break;
                    case 6:
                        this.handlePurchase(shopNumGen.getBusiId(), shopNumGen.getMarkCode());
                        break;
                }
            }
            channel.basicAck(deliveryTag, true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            channel.basicReject(deliveryTag, false);
        }
    }

    /**
     * 处理采购商shopNum
     *
     * @param id
     */
    private void handlePurchase(Long id, Integer markCode) {
        InfoPurchase purchase = purchaseService.getById(id);
        if (purchase != null
                && (purchase.getShopNum() == null || purchase.getShopNum() == 0)) {
            Long genNum = mysqlShopNumHelper.genShopNum(markCode);
            if (genNum != null) {
                String strNum = String.format("%d%06d", markCode, genNum);
                UpdateWrapper<InfoPurchase> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("Id", id);
                purchase = new InfoPurchase();
                purchase.setShopNum(Long.valueOf(strNum));
                purchaseService.update(purchase, updateWrapper);
            }
        }
    }

    /**
     * 处理果农shopNum
     *
     * @param id
     */
    private void handleFarmer(Long id, Integer markCode) {
        InfoFarmer farmer = farmerService.getById(id);
        if (farmer != null
                && (farmer.getShopNum() == null || farmer.getShopNum() == 0)) {
            Long genNum = mysqlShopNumHelper.genShopNum(markCode);
            if (genNum != null) {
                String strNum = String.format("%d%06d", markCode, genNum);
                UpdateWrapper<InfoFarmer> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("Id", id);
                farmer = new InfoFarmer();
                farmer.setShopNum(Long.valueOf(strNum));
                farmerService.update(farmer, updateWrapper);
            }
        }
    }

    /**
     * 处理分拣、农资、包装shopNum
     *
     * @param id
     */
    private void handleBusiness(Long id, Integer markCode) {
        InfoBusiness business = businessService.getById(id);
        if (business != null
                && (business.getShopNum() == null || business.getShopNum() == 0)) {
            Long genNum = mysqlShopNumHelper.genShopNum(markCode);
            if (genNum != null) {
                String strNum = String.format("%d%06d", markCode, genNum);
                UpdateWrapper<InfoBusiness> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("Id", id);
                business = new InfoBusiness();
                business.setShopNum(Long.valueOf(strNum));
                businessService.update(business, updateWrapper);
            }
        }
    }
}
